import AuthTreeFormItem from '@/component/AuthTreeFormItem';
import { getProgramOptions, givePermissionApi } from '@/services/api';
import {
  DrawerForm,
  ProFormDigit,
  ProFormInstance,
  ProFormItem,
  ProFormSelect,
} from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Form, message } from 'antd';
import { isEqual } from 'lodash';
import React, { useEffect, useRef } from 'react';

interface Props {
  open?: boolean;
  info?: any;
  close?: () => void;
  onFinsh?: () => void;
}
// 新增/编辑用户
const CreateMerchantConfig: React.FC<Props> = ({
  open,
  close,
  info,
  onFinsh,
}) => {
  const [form] = Form.useForm<{ name: string; company: string }>();

  const formRef = useRef<ProFormInstance>();

  useEffect(() => {
    if (info) {
      setTimeout(() => {
        formRef?.current?.setFieldsValue({
          ...info,
        });
      }, 20);
    }
  }, [info]);

  // 查询所有商户
  const { data: merchantList } = useRequest(async () => {
    const _res = await getProgramOptions();

    return _res?.data;
  });

  return (
    <DrawerForm
      formRef={formRef}
      title={info.id ? '编辑' : '新建'}
      form={form}
      open={open}
      width={'38%'}
      onOpenChange={(visible) => {
        if (!visible) {
          close?.();
        }
      }}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
      }}
      onFinish={async (values) => {
        try {
          const { msg } = await givePermissionApi(values?.user, {
            auths: values?.auths?.join(','),
            divided: values?.divided,
            newcomer: values?.newcomer,
            oneness: values?.oneness,
          });
          onFinsh?.();
          message.success(msg);
          // 不返回不会关闭弹框
          return true;
        } catch (error) {}
      }}
    >
      <ProFormSelect
        name="user"
        label="商户"
        disabled={!!info?.id}
        rules={[
          {
            required: true,
          },
        ]}
        options={merchantList ?? []}
      ></ProFormSelect>

      <ProFormDigit
        name="newcomer"
        label="拉新金额"
        rules={[
          {
            required: true,
          },
        ]}
      ></ProFormDigit>

      <ProFormDigit
        name="oneness"
        label="车电一体金额"
        rules={[
          {
            required: true,
          },
        ]}
      ></ProFormDigit>

      <ProFormDigit
        name="divided"
        label="分成比例"
        rules={[
          {
            required: true,
          },
        ]}
        addonAfter={'%'}
      ></ProFormDigit>

      <ProFormItem
        name="auths"
        label="配置权限"
        rules={[
          {
            required: true,
          },
        ]}
      >
        <AuthTreeFormItem />
      </ProFormItem>
    </DrawerForm>
  );
};

export default React.memo(CreateMerchantConfig, (prev, next) =>
  isEqual(prev, next),
);
